/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package edu.upf.grupE.impl;

import edu.upf.grupE.Controller.VideoController;
import edu.upf.grupE.Listener;
import edu.upf.grupE.Video.AVTransmit2;
import java.net.UnknownHostException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.media.MediaLocator;
import org.jivesoftware.smack.packet.Message;
import org.jivesoftware.smack.packet.Packet;

import edu.upf.grupE.Entities.Video;
import java.net.InetAddress;

/**
 *
 * @author xday666
 */
public class VideoRequestListener implements Listener {

    private IM im;

    /**
     *
     * @param instancem
     */
    public VideoRequestListener(final IM instancem) {
        im = instancem;
    }

    /**
     * we only work with the packets that are Messages. then we create a new Message
     * that will be the response to the search profile Message.
     * To be sure that the information that arrives to this listener is correct, we
     * print it into the Text Box.
     * Later we send back to the origin a Message containing the same object received.
     * @param packet
     */
    public final void processPacket(final Packet packet) {
        if (packet instanceof Message) {


            Message msg = (Message) packet;

            String ip = (String) msg.getProperty("ip");
            String port = (String) msg.getProperty("port");
            String videoid = (String) msg.getProperty("videoid");

            String path = ((Video) VideoController.getById(Long.parseLong(videoid))).getFileDescriptor().getPath();


            // Prepare path to be treated.
            path = "file:/" + path;

            // Create an audio transmit object with the specified params.
            AVTransmit2 at = new AVTransmit2(new MediaLocator(path), ip, port);

            // Invoque start method that initializes the transmission
            at.start();



            InetAddress address;
            try {
                address = InetAddress.getLocalHost();
                ip = (String) address.getHostAddress();
            } catch (UnknownHostException ex) {
                Logger.getLogger(VideoRequestListener.class.getName()).log(Level.SEVERE, null, ex);
            }




            im.responseVideo(msg.getFrom(), ip, port);
        }
    }
}
